package com.mnb.beidou.handler;

import com.mnb.beidou.service.TcpMessageService;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * TCP服务器通道初始化器
 */
@Component
public class TcpServerInitializer extends ChannelInitializer<SocketChannel> {

    @Autowired
    private TcpMessageService messageService;

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        
        // 添加编解码器
        pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
        pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
        
        // 添加自定义处理器（每个连接都会创建新的实例）
        pipeline.addLast(new TcpServerChannelHandler(messageService));
    }
}
